package com.deng.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deng.api.entity.*;
import com.deng.api.mapper.*;
import com.deng.api.service.ICloudRecruitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deng.api.vo.DistributionVO;
import com.deng.api.vo.PageVO;
import com.deng.api.vo.RecruitADDVO;
import com.deng.commons.common.BaseResult;
import com.deng.commons.common.ErrorCode;
import com.deng.commons.utils.AccountValidatorUtil;
import com.deng.commons.utils.ToolUtils;
import com.deng.commons.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.core.internal.runtime.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p>
 * 投递简历人员表 服务实现类
 * </p>
 *
 * @author deng
 * @since 2022-08-10
 */
@Service
@Slf4j
public class CloudRecruitServiceImpl extends ServiceImpl<CloudRecruitMapper, CloudRecruit> implements ICloudRecruitService {
    @Resource
    private CloudRecruitMapper cloudRecruitMapper;
    @Resource
    private CloudChannelMapper cloudChannelMapper;
    @Resource
    private CloudCompanyMapper cloudCompanyMapper;
    @Resource
    private CloudCityMapper cloudCityMapper;
    @Resource
    private CloudProductMapper cloudProductMapper;
    @Resource
    private CloudRecruitDetailMapper cloudRecruitDetailMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    @Transactional
    public boolean add(RecruitADDVO recruitADDVO) {
        //进行数据校验，校验绑定关系、联系方式、招聘者信息是否存在
        CloudChannel c = cloudChannelMapper.selectById(recruitADDVO.getSourceId());
        CloudCompany company = cloudCompanyMapper.selectById(recruitADDVO.getCompanyId());
        CloudProduct product = cloudProductMapper.selectById(recruitADDVO.getProductId());
        if (c == null || company==null || product == null){
            log.info(" 参数不正确");
            return false;
        }
        //校验手机号码
        if (!AccountValidatorUtil.isMobile(recruitADDVO.getPhone())){
            log.info(" 手机格式不正确！");
            return false;
        }
        //招聘者信息是否存在,重复投递
        LambdaQueryWrapper<CloudRecruit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CloudRecruit::getPhone,recruitADDVO.getPhone());
        CloudRecruit recruit = cloudRecruitMapper.selectOne(wrapper);
        if (recruit != null){
            log.info(" 招聘信息已经存在！");
            recruit.setRepetition(1);
            recruit.setRepeatTime(LocalDateTime.parse(DateUtil.now()));
            cloudRecruitMapper.updateById(recruit);
            return false;
        }
        //添加招聘者信息
        CloudRecruit r = new CloudRecruit();
        BeanUtil.copyProperties(recruitADDVO,r);
        AuthUser user = (AuthUser) UserUtils.getUser();
        r.setInputId(Math.toIntExact(user.getId()));
        r.setInputName(user.getUsername());
        r.setRepetition(0);
        cloudRecruitMapper.insert(r);
        //添加详情
        CloudRecruitDetail detail = new CloudRecruitDetail();
        detail.setRecruitId(r.getId());
        detail.setAddress(recruitADDVO.getAddress());
        detail.setSchool(recruitADDVO.getSchool());
        if (!StrUtil.isEmptyIfStr(recruitADDVO.getCard())){
            Map<String, Object> map = ToolUtils.cardChange(recruitADDVO.getCard());
            Date birthday = (Date) map.get("birthday");
            //将date类型转为localDate
            detail.setBirthday(birthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            detail.setCard(recruitADDVO.getCard());
        }
        cloudRecruitDetailMapper.insert(detail);
        return true;
    }

    @Override
    public boolean importRecruit(MultipartFile file) {
        //解析Excel
        try {
            ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> list = excelReader.read(1);
            //转换对象
            list.forEach(row->{
                RecruitADDVO vo = new RecruitADDVO();
                vo.setName(row.get(0).toString());
                vo.setSex(row.get(1).toString());
                //存放公司信息
                String companyName = row.get(2).toString();
                if (!StrUtil.isEmptyIfStr(companyName)){
                    CloudCompany company = cloudCompanyMapper.selectOne(new QueryWrapper<CloudCompany>().eq("name", companyName));
                    if (company != null){
                        vo.setCompanyId(Long.valueOf(company.getId()));
                    }
                }
                vo.setPhone(row.get(3).toString());
                vo.setEmail(row.get(4).toString());
                vo.setQq(row.get(5).toString());
                vo.setWeixin(row.get(6).toString());
                vo.setMajor(row.get(7).toString());
                vo.setDegree(getDegree(row.get(8).toString()));
                //城市信息
                String cityName = row.get(9).toString();
                if (!StrUtil.isEmptyIfStr(cityName)){
                    CloudCity city = cloudCityMapper.selectOne(new QueryWrapper<CloudCity>().eq("name", cityName));
                    if (city != null){
                        vo.setCityId(Long.valueOf(city.getId()));
                    }
                }
                //渠道、来源
                String channel = row.get(10).toString();
                if (!StrUtil.isEmptyIfStr(channel)){
                    CloudChannel c = cloudChannelMapper.selectOne(new QueryWrapper<CloudChannel>()
                            .eq("name", channel));
                    if (c != null){
                        vo.setChannelId(Long.valueOf(c.getId()));
                        //来源
                        String source = row.get(11).toString();
                        LambdaQueryWrapper<CloudChannel> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(CloudChannel::getName,source);
                        wrapper.eq(CloudChannel::getChannelId,c.getId());
                        CloudChannel s = cloudChannelMapper.selectOne(wrapper);
                        vo.setSourceId(Long.valueOf(s.getId()));
                    }
                }
                vo.setJobs(row.get(12).toString());
                //产品
                String productName = row.get(13).toString();
                if (!StrUtil.isEmptyIfStr(productName)){
                    CloudProduct product = cloudProductMapper.selectOne(new QueryWrapper<CloudProduct>()
                            .eq("product", productName));
                    if (product != null){
                        vo.setProductId(Long.valueOf(product.getId()));
                    }
                }
                //资源录入时间和人事专员
                vo.setSourceTime(row.get(14).toString());
                vo.setInputName(row.get(15).toString());
                this.add(vo);
            });
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public PageVO getAll(Integer page, Integer size, CloudRecruit cloudRecruit) {
        Page<CloudRecruit> p = new Page<>(page,size);
        LambdaQueryWrapper<CloudRecruit> wrapper = new LambdaQueryWrapper<>();
        //根据名字或者手机号码搜索
        String nameOrPhone = cloudRecruit.getName();
        if (!StrUtil.isEmptyIfStr(nameOrPhone)){
            wrapper.like(CloudRecruit::getName,nameOrPhone).or()
                    .like(CloudRecruit::getPhone,nameOrPhone);
        }
        //根据公司查找
        if (cloudRecruit.getCompanyId() != null && cloudRecruit.getCompanyId()>0){
            wrapper.eq(CloudRecruit::getCompanyId,cloudRecruit.getCompanyId());
        }
        //分配状态查找
        if (cloudRecruit.getDistributeState() != null){
            wrapper.eq(CloudRecruit::getDistributeState,cloudRecruit.getDistributeState());
        }
        return PageVO.toPageVO(cloudRecruitMapper.selectPage(p,wrapper));
    }

    @Override
    @Transactional
    public BaseResult deleteRecruit(Set<Long> ids) {
        //用来判断是否全部删除成功的
        AtomicBoolean flag = new AtomicBoolean(true);
        //如果招聘信息已经分配给人事专员则不能删除
        ids.forEach(id->{
            CloudRecruit recruit = cloudRecruitMapper.selectById(id);
            //未分配可以删除
            if (recruit.getDistributeState() == 0){
                //删除招聘详情
                LambdaQueryWrapper<CloudRecruitDetail> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(CloudRecruitDetail::getRecruitId,id);
                cloudRecruitDetailMapper.delete(wrapper);
                //删除招聘信息
                cloudRecruitMapper.deleteById(id);
            }else{
                flag.set(false);
            }
        });
        if (flag.get()){
            return BaseResult.success();
        }
        return BaseResult.success(ErrorCode.CODE_1030);
    }

    @Override
    public BaseResult distribution(DistributionVO vo) {
        //判断要分配的人事专员是否存在或可用
        SysUser user = sysUserMapper.selectById(vo.getUserId());
        if (user == null || user.getEnabled().equals("false")){
            return BaseResult.fail(ErrorCode.CODE_1031);
        }

        for (Long id: vo.getRecruitIds()){
            CloudRecruit recruit = cloudRecruitMapper.selectById(id);
            //要分配的招聘信息是未分配
            if (!recruit.getDistributeState().equals(0)){
                return BaseResult.fail(ErrorCode.CODE_1032);
            }
            // 分配，修改分配状态和相关信息即可
            recruit.setDistributeState(1);
            recruit.setDistributeTime(LocalDateTime.parse(DateUtil.now(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            //分配人信息
            recruit.setUserId(Math.toIntExact(user.getId()));
            recruit.setUserName(user.getUsername());
            //录入人信息
            AuthUser u = (AuthUser) UserUtils.getUser();
            recruit.setInputId(Math.toIntExact(u.getId()));
            recruit.setInputName(u.getUsername());
            cloudRecruitMapper.updateById(recruit);
        }
        return BaseResult.success();
    }

    @Override
    public BaseResult getNew(Integer page, Integer size, CloudRecruit cloudRecruit) {
        Page<CloudRecruit> p = new Page<>(page,size);
        LambdaQueryWrapper<CloudRecruit> wrapper = new LambdaQueryWrapper<>();
        //已分配
        wrapper.eq(CloudRecruit::getDistributeState,1);
        String nameOrPhone = cloudRecruit.getName();
        //根据账号或者手机号搜索
        if (!StrUtil.isEmptyIfStr(nameOrPhone)){
            wrapper.like(CloudRecruit::getName,cloudRecruit.getName())
                    .or().like(CloudRecruit::getPhone,cloudRecruit.getName());
        }
        //根据账号id查询
        AuthUser user = (AuthUser) UserUtils.getUser();
        wrapper.eq(CloudRecruit::getUserId,user.getId());
        //根据跟踪次数来判断, 跟踪次数为0
        wrapper.lt(CloudRecruit::getTailNum,1);
        return BaseResult.success(PageVO.toPageVO(cloudRecruitMapper.selectPage(p,wrapper)));
    }

    public Integer getDegree(String str){
        if (StrUtil.isEmptyIfStr(str)){
            return 0;
        }
        if (str.contains("小学")){
            return 1;
        }
        if (str.contains("初中")){
            return 2;
        }
        if (str.contains("高中")){
            return 3;
        }
        if (str.contains("大专")){
            return 4;
        }
        if (str.contains("本科")){
            return 5;
        }
        if (str.contains("硕士")){
            return 6;
        }
        if (str.contains("博士")){
            return 7;
        }
        return -1;
    }
}
